# -*- coding: utf-8 -*-
"""
    flask_celery3.command
    ~~~~~~~~~~~~~~~~~~~~~

    Add celery command with Flask-Script

    :copyright: (c) 2016 by Degang Sheng.
    :license: BSD, see LICENSE for more details.
"""

import os

from flask import current_app
from flask_script import Manager

__all__ = ['CeleryCommand']

CeleryCommand = Manager(usage='Celery commands')


@CeleryCommand.option('-l', '--loglevel',
                      dest='loglevel', default='info', type=str,
                      help='Celery logger level (default is \'INFO\')')
@CeleryCommand.option('-f', '--logfile',
                      dest='logfile', default=None, type=str,
                      help='Path to log file. If no logfile is specified, '
                           'stderr is used')
@CeleryCommand.option('-c', '--concurrency',
                      dest='concurrency', type=int,
                      help='The number of worker processes/threads '
                           '(default is the number of CPUs available)')
@CeleryCommand.option('--version',
                      dest='version', default=None, type=str,
                      help='Show program\'s version number and exit')
def worker(**kwargs):
    """Start celery worker"""
    opt = ['celery', 'worker']
    for k, v in kwargs.items():
        if v:
            opt.append('--%s=%s' % (k, v))
    app = current_app.extensions['celery3'].celery
    app.start(opt)


@CeleryCommand.option('-l', '--loglevel',
                      dest='loglevel', default='info', type=str,
                      help='Celery logger level (default is \'INFO\')')
@CeleryCommand.option('-f', '--logfile',
                      dest='logfile', default=None, type=str,
                      help='Path to log file. If no logfile is specified, '
                           'stderr is used')
@CeleryCommand.option('-S', '--scheduler',
                      dest='scheduler', default=None, type=str,
                      help='Using custom scheduler classes')
@CeleryCommand.option('--workdir',
                      dest='workdir', default=None, type=str,
                      help='Optional directory to change to after '
                           'detaching (default is ./temp/celerybeat)')
@CeleryCommand.option('--version',
                      dest='version', default=None, type=str,
                      help='Show program\'s version number and exit')
def beat(**kwargs):
    """Start celery beat"""
    opt = ['celery', 'beat']
    for k, v in kwargs.items():
        if v:
            opt.append('--%s=%s' % (k, v))
        elif k == 'workdir':
            # Create default work dir
            directory = os.path.join('temp', 'celery')
            if not os.path.exists(directory):
                os.makedirs(directory)
            opt.append('--workdir=%s' % directory)
    app = current_app.extensions['celery3'].celery
    app.start(opt)